package com.shuqing.download.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.shuqing.download.config.DruidCommonConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 全量数据源的连接池配置
 *
 * @author libing
 * @date 2021/12/28 9:46
 */
@Slf4j
@Configuration
@MapperScan(basePackages = {"com.shuqing.download.mapper.full"}, sqlSessionTemplateRef = "sqlSessionTemplateFull")
public class FullDataSourceDruidConfig extends DruidCommonConfig {

    @Value("${owner.datasource.instance.full.dbUrl}")
    private String dbUrl;
    @Value("${owner.datasource.instance.full.username}")
    private String username;
    @Value("${owner.datasource.instance.full.password}")
    private String password;

    @Bean("dataSourceFull")
    public DataSource dataSource() {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        super.dataSourceSetParam(datasource);
        return datasource;
    }

    @Bean(name = "sqlSessionFactoryFull")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();
        factory.setDataSource(dataSource());
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factory.setMapperLocations(resolver.getResources("classpath*:/mapper/full/*.xml"));
        return factory.getObject();
    }

    @Bean(name = "transactionManagerFull")
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean(name = "sqlSessionTemplateFull")
    public SqlSessionTemplate sqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory());
    }

}